import 'package:flutter/material.dart';
import '../models/acceptance_form.dart';
import '../services/acceptance_service.dart';

class AcceptanceProgressScreen extends StatefulWidget {
  final String formNumber;

  const AcceptanceProgressScreen({
    super.key,
    required this.formNumber,
  });

  @override
  State<AcceptanceProgressScreen> createState() => _AcceptanceProgressScreenState();
}

class _AcceptanceProgressScreenState extends State<AcceptanceProgressScreen> {
  final AcceptanceService _acceptanceService = AcceptanceService();
  AcceptanceForm? _form;
  bool _isLoading = true;
  int _selectedStatus = 1; // 1: 待处理, 2: 处理中, 3: 已完成

  @override
  void initState() {
    super.initState();
    _loadForm();
  }

  Future<void> _loadForm() async {
    setState(() => _isLoading = true);
    try {
      final form = await _acceptanceService.getAcceptanceFormByNumber(widget.formNumber);
      if (mounted) {
        setState(() {
          _form = form;
          _selectedStatus = form.status;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('加载受理单失败: $e'),
            action: SnackBarAction(
              label: '重试',
              onPressed: _loadForm,
            ),
          ),
        );
      }
    }
  }

  Future<void> _updateStatus() async {
    if (_form == null) return;

    setState(() => _isLoading = true);
    try {
      final updatedForm = AcceptanceForm(
        formNumber: _form!.formNumber,
        acceptanceDate: _form!.acceptanceDate,
        applicantName: _form!.applicantName,
        applicantPhone: _form!.applicantPhone,
        applicantIdCard: _form!.applicantIdCard,
        respondentName: _form!.respondentName,
        respondentPhone: _form!.respondentPhone,
        respondentIdCard: _form!.respondentIdCard,
        disputeDescription: _form!.disputeDescription,
        acceptorName: _form!.acceptorName,
        acceptorUnit: _form!.acceptorUnit,
        acceptorPhone: _form!.acceptorPhone,
        categoryId: _form!.categoryId,
        status: _selectedStatus,
      );

      await _acceptanceService.updateAcceptanceForm(updatedForm);
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('状态更新成功')),
        );
        Navigator.pop(context, true); // 返回并刷新列表
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('状态更新失败: $e')),
        );
      }
    }
  }

  String _getStatusText(int status) {
    switch (status) {
      case 1:
        return '待处理';
      case 2:
        return '处理中';
      case 3:
        return '已完成';
      default:
        return '未知状态';
    }
  }

  Color _getStatusColor(int status) {
    switch (status) {
      case 1:
        return const Color(0xFF2563EB); // 蓝色
      case 2:
        return const Color(0xFFEA580C); // 橘黄色
      case 3:
        return const Color(0xFF10B981); // 绿色
      default:
        return const Color(0xFF1E293B);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8FAFC),
      appBar: AppBar(
        title: const Text('进度管理'),
        actions: [
          if (_form != null && !_isLoading)
            TextButton.icon(
              onPressed: _updateStatus,
              icon: const Icon(
                Icons.save_alt_rounded,
                color: Color(0xFF10B981),
                size: 20,
              ),
              label: const Text(
                '保存',
                style: TextStyle(
                  color: Color(0xFF10B981),
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
              ),
              style: TextButton.styleFrom(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                  side: const BorderSide(
                    color: Color(0xFF10B981),
                    width: 1.5,
                  ),
                ),
              ),
            ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _form == null
              ? const Center(child: Text('未找到受理单'))
              : SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 基本信息
                      const Text(
                        '基本信息',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: Color(0xFF1E293B),
                        ),
                      ),
                      const SizedBox(height: 16),
                      TextFormField(
                        decoration: const InputDecoration(
                          labelText: '受理单号',
                          border: OutlineInputBorder(),
                        ),
                        initialValue: _form!.formNumber,
                        readOnly: true,
                        style: const TextStyle(color: Colors.red),
                      ),
                      const SizedBox(height: 16),
                      TextFormField(
                        decoration: const InputDecoration(
                          labelText: '受理日期',
                          border: OutlineInputBorder(),
                        ),
                        initialValue: _form!.acceptanceDate.toString().split(' ')[0],
                        readOnly: true,
                      ),
                      const SizedBox(height: 16),
                      DropdownButtonFormField<int>(
                        decoration: InputDecoration(
                          labelText: '当前状态',
                          labelStyle: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Color(0xFF1E293B),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                            borderSide: const BorderSide(
                              color: Color(0xFF2563EB),
                              width: 2,
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                            borderSide: const BorderSide(
                              color: Color(0xFF2563EB),
                              width: 2,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                            borderSide: const BorderSide(
                              color: Color(0xFF2563EB),
                              width: 2,
                            ),
                          ),
                          filled: true,
                          fillColor: const Color(0xFFEFF6FF),
                          contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                        ),
                        value: _selectedStatus,
                        items: [
                          DropdownMenuItem(
                            value: 1,
                            child: Text(
                              '待处理',
                              style: const TextStyle(
                                color: Color(0xFF2563EB), // 蓝色
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          DropdownMenuItem(
                            value: 2,
                            child: Text(
                              '处理中',
                              style: const TextStyle(
                                color: Color(0xFFEA580C), // 橘黄色
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          DropdownMenuItem(
                            value: 3,
                            child: Text(
                              '已完成',
                              style: const TextStyle(
                                color: Color(0xFF10B981), // 绿色
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                        onChanged: (value) {
                          if (value != null) {
                            setState(() => _selectedStatus = value);
                          }
                        },
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: _getStatusColor(_selectedStatus),
                        ),
                      ),
                      const SizedBox(height: 24),

                      // 申请人信息
                      const Text(
                        '申请人信息',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: Color(0xFF1E293B),
                        ),
                      ),
                      const SizedBox(height: 16),
                      TextFormField(
                        decoration: const InputDecoration(
                          labelText: '申请人姓名',
                          border: OutlineInputBorder(),
                        ),
                        initialValue: _form!.applicantName,
                        readOnly: true,
                      ),
                      const SizedBox(height: 16),
                      TextFormField(
                        decoration: const InputDecoration(
                          labelText: '申请人电话',
                          border: OutlineInputBorder(),
                        ),
                        initialValue: _form!.applicantPhone,
                        readOnly: true,
                      ),
                      const SizedBox(height: 24),

                      // 纠纷信息
                      const Text(
                        '纠纷信息',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: Color(0xFF1E293B),
                        ),
                      ),
                      const SizedBox(height: 16),
                      TextFormField(
                        decoration: const InputDecoration(
                          labelText: '纠纷描述',
                          border: OutlineInputBorder(),
                          alignLabelWithHint: true,
                        ),
                        initialValue: _form!.disputeDescription,
                        maxLines: 3,
                        readOnly: true,
                      ),
                    ],
                  ),
                ),
    );
  }
} 